package com.lagou.worker.controller;

import com.lagou.worker.api.MailService;
import com.lagou.worker.service.LagouAuthCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @ClassName CodeController
 * @Description TODO
 * @Author xsq
 * @Date 2020/7/28 16:20
 **/
@RestController
@RequestMapping("/code")
@Slf4j
public class CodeController {

    @Autowired
    private LagouAuthCodeService lagouAuthCodeService;

    @Reference
    private MailService mailService;

    @GetMapping("/create/{email}")
    public ResponseEntity getLoginUrl(@PathVariable("email") String email) {
        String code = getValidationCode();
        //把验证码发送到邮箱
        Boolean falg = mailService.sendEmail(email, code);
        if (falg) {
            lagouAuthCodeService.setEmailCode(email, code);
            log.info("-------验证码发送成功-------：" + code);
            return ResponseEntity.ok(true);
        }
        return ResponseEntity.badRequest().body("验证码发送失败");
    }


    /**
     * 获取6位随机验证码
     *
     * @return
     */
    private static String getValidationCode() {
        return String.valueOf((new Random().nextInt(899999) + 100000));
    }


}
